<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Composition;
use Illuminate\Database\DetectsDeadlocks;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class CompositionController extends Controller{
    //前端展示
    public function index(){
        $article = Composition::where('partid',Auth::user()->partid)->where('active','0')->paginate(10);
        return view('akl.Aikla.Composition-index',compact('article'));
    }
    //后台展示
    public function show(){
        $composition = Composition::where('partid',Auth::user()->partid)->where('active','0')->paginate(10);
        return view('akl.Admin.Composition_index',compact('composition'));
    }
    //返回编辑页面
    public function edit($com_id){
        $Composition = Composition::where('com_id',$com_id)->first();
        return view('akl.Admin.Composition_edit',compact('Composition'));
    }
    //更新分类提交数据
    public function update(Request $request,$com_id){
        $input = Input::except('_token','_method','file');
        if($request->get('imgs')[0]) $input['com_url'] = $request->get('imgs')[0];
        $state = Composition::where('com_id',$com_id)->update($input);
        if ($state){
            return redirect(url('Admin/Composition/index'));
        }else{
            return back()->withErrors('分类信息更新失败!');
        }
    }
    //返回添加页面
    public function create(){
        return view('akl.Admin.Composition_add');
    }
    //添加分类提交数据
    public function store( Request $request ){
        $input = Input::except('_token');
        $rules = [
            'com_name'=>'required',
        ];
        $mes = [
            'com_name.required'=>'分类名不能为空!',
        ];
        $va =  Validator::make($input,$rules,$mes);
        if ($va->passes()){
            $input['partid'] = Auth::user()->partid;
            $input['com_url'] = $request->get('imgs')[0];
            $state = Composition::create($input);
            if ($state){
                return redirect(url('Admin/Composition/index'));
            } else{
                return back()->withErrors('数据提交失败,请稍后再试!');
            }
        }else{
            return back()->withErrors($va);
        }

    }
    public function delete($id ){
       $state = Composition::where('com_id',$id)->where('partid',Auth::user()->partid)->update(['active'=>'1']);
       if($state==1){
           return redirect(url('Admin/Composition/index'));
       }else{
           return back()->withErrors('分类删除失败');
       };
    }
}